package net.studio.simpletetris.widget;

import net.studio.simpletetris.control.DrawThread;
import net.studio.simpletetris.control.Game;
import net.studio.simpletetris.intf.IField;
import net.studio.simpletetris.intf.IGameView;
import net.studio.simpletetris.intf.ISizeListener;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameView extends SurfaceView implements SurfaceHolder.Callback, IGameView {

	protected IField field = null;
	
	protected ISizeListener sizeListener;
	
	protected DrawThread drawThread;
	
	protected int blockSize = 0;
	
	protected float frameX = 0;
	protected float frameY = 0;
	

	public GameView(Context context) {
		this(context, null);
	}

    public GameView(Context context, AttributeSet attributeSet) {
        this(context, attributeSet, 0);
    }

    public GameView(Context context, AttributeSet attributeSet, int defStyle) {
        super(context, attributeSet, defStyle);
        getHolder().addCallback(this);
        
        setZOrderOnTop(true);
        getHolder().setFormat(PixelFormat.TRANSLUCENT);
    }

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	public void surfaceCreated(SurfaceHolder holder) {
		drawThread = new DrawThread(getHolder(), getResources()) {
			public void renderLoop(Canvas canvas) {
				if (Game.instance != null) {
					if (field != null) {
						Game.instance.drawField(GameView.this, canvas, field);
					}
				}
			}			
		};
		drawThread.setRunning(true);
		drawThread.start();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		drawThread.setRunning(false);
		while (retry) {
			try {
				drawThread.join();
				retry = false;
			} catch (InterruptedException e) {
				
			}
		}
		drawThread = null;
	}
	
	@Override
    protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld)
    {        
        super.onSizeChanged(xNew, yNew, xOld, yOld);

        if (sizeListener != null)
        	sizeListener.onSizeChanged(this, xNew, yNew, xOld, yOld);
    }

	public ISizeListener getSizeListener() {
		return sizeListener;
	}

	public void setSizeListener(ISizeListener sizeListener) {
		this.sizeListener = sizeListener;
	}

	public int getBlockSize() {
		return blockSize;
	}

	public float getFrameX() {
		return frameX;
	}

	public float getFrameY() {
		return frameY;
	}

	synchronized public IField getField() {
		return field;
	}

	synchronized public void setField(IField value) {
		this.field = value;
	}

	public void setBlockSize(int blockSize) {
		this.blockSize = blockSize;
	}

	public void setFrameX(float frameX) {
		this.frameX = frameX;
	}

	public void setFrameY(float frameY) {
		this.frameY = frameY;
	}

}